// pages/addnews/addnews.js
const app = getApp();
const db = wx.cloud.database();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgList: []
    },

    formSubmit: function(e) {

        let imgs = [];

        wx.showLoading({
          title: '数据上传中......',
        })
        let promiseArr = [];
        for(let i=0;i<this.data.imgList.length;i++) {
          let promise = new Promise( (resovle, reject) => {
            wx.cloud.uploadFile({
              cloudPath: 'newsImage/' + new Date().getTime() + 'png',
              filePath: this.data.imgList[i],

              success: res => {
                console.log(res.fileID);
                imgs = imgs.concat(res.fileID);
                console.log(imgs);
                resovle(res);
              },

              fail: err => {
                reject(err);
              }
            });
          });
          promiseArr.push(promise);
        }

        Promise.all(promiseArr).then(res => {
          this.setData({
            imgList: imgs
          });
        });

        if(e.type == 'submit') {
          let news = {
            newsId: this.data.length + 1,
            title: e.detail.value.title,
            content: e.detail.value.content,
            author: 'anonymous',
            avatarUrl: '',
            imgsUrl: this.data.imgList,
            date: new Date(),
            readingStatus: false,
            readingNum: 0,
            likeStatus: false,
            likeNum: 0,
            commentStatus: false,
            commentNum: 0,
            comment: []
          }
          db.collection('news').add({
            data: news
          })
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                title: '上传完成！',
              })
            },
          })
          wx.reLaunch({
            url: '/pages/home/home',
          })
        }
    },

    ChooseImage() {
        wx.chooseImage({
          count: 4, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album'], //从相册选择
          success: (res) => {
            if (this.data.imgList.length != 0) {
              this.setData({
                imgList: this.data.imgList.concat(res.tempFilePaths)
              })
            } else {
              this.setData({
                imgList: res.tempFilePaths
              })
            }
          }
        });
      },

    ViewImage(e) {
        wx.previewImage({
          urls: this.data.imgList,
          current: e.currentTarget.dataset.url
        });
    },

    DelImg(e) {
        wx.showModal({
          title: '召唤师',
          content: '确定要删除这段回忆吗？',
          cancelText: '再看看',
          confirmText: '再见',
          success: res => {
            if (res.confirm) {
              this.data.imgList.splice(e.currentTarget.dataset.index, 1);
              this.setData({
                imgList: this.data.imgList
              })
            }
          }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      db.collection('news').get().then(res => {
        this.setData({
          length: res.data.length
        });
      });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})